//Namespace Reference

using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;

namespace Promike.site.Helpers
{
    public class ImageHelper
    {
        public static Bitmap Resize(Image img, int lnWidth, int lnHeight)
        {
            var orientation = img.ExifOrientation().ToString();
            float degree = 0;
            switch (orientation)
            {
                case "TopLeft": degree = -90; break;
                case "TopRight": degree = 90; break;
                case "BottomRight": degree = -270; break;
                case "BottomLeft": degree = 270; break;
                case "LeftTop": degree = 0; break;
                case "RightTop": degree = 90; break;
                case "RightBottom": degree = -180; break;
                case "LeftBottom": degree = 180; break;
            }

            Bitmap bmpOut;
            try
            {
                var loBmp = new Bitmap(img);

                decimal lnRatio;
                int lnNewWidth;
                int lnNewHeight;

                if (loBmp.Width < lnWidth && loBmp.Height < lnHeight)
                {
                    var g1 = Graphics.FromImage(loBmp);
                    g1.RotateTransform(degree);
                    return loBmp;
                }

                if (loBmp.Width > loBmp.Height)
                {
                    lnRatio = (decimal)lnWidth / loBmp.Width;
                    lnNewWidth = lnWidth;
                    var lnTemp = loBmp.Height * lnRatio;
                    lnNewHeight = (int)lnTemp;
                }
                else
                {
                    lnRatio = (decimal)lnHeight / loBmp.Height;
                    lnNewHeight = lnHeight;
                    var lnTemp = loBmp.Width * lnRatio;
                    lnNewWidth = (int)lnTemp;
                }

                bmpOut = new Bitmap(lnNewWidth, lnNewHeight);

                var g = Graphics.FromImage(bmpOut);
               
                g.InterpolationMode = InterpolationMode.Default;
                g.SmoothingMode = SmoothingMode.HighSpeed;
                g.CompositingQuality = CompositingQuality.HighSpeed;
                g.PixelOffsetMode = PixelOffsetMode.HighSpeed;
                g.FillRectangle(Brushes.White, 0, 0, lnNewWidth, lnNewHeight);
                g.DrawImage(loBmp, degree, 0, lnNewWidth, lnNewHeight);

                loBmp.Dispose();
            }
            catch
            {
                return null;
            }
            return bmpOut;
        }
    }
}